import datetime
import json
import os
import uuid

from django.core.paginator import Paginator
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from back.dbservice import UserService, ArticleService, RecommentService
from back.models import UIResult
# Create your views here.
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)
#登录
def login(request):
    if request.method=='GET':
        return render(request,'back/login.html')
    else:
        #接受表单提交的数据
        uname=request.POST['username']
        upwd=request.POST['password']
        uobj=UserService.findByname(uname)
        if uobj:#如果存在该对象，判断用户名和密码
            if upwd==uobj.pwd:
                #需要更新登录的时间    datetime.datetime.now()
                UserService.updateTime(uobj.uname)
                #将登陆信息保存在容器（session）
                request.session['name']=uname
                return HttpResponse(UIResult(True), content_type='application/json')
            else:
                return HttpResponse(UIResult(False,'密码不正确'), content_type='application/json')
        else:
            return HttpResponse(UIResult(False,'此用户不存在'),content_type='application/json')
#后台首页
def index(request):
    uname=request.session.get('name')
    print(uname)
    if uname:
        return render(request,'back/index.html')
    else:
        return render(request,'back/login.html',{'errorMsg':'请先登陆......'})

#安全退出
def signout(request):
    request.session['name']=''
    pas=''
    context={'password':pas}
    return render(request,'back/login.html',context)
#修改密码
def changepwd(request):
    if request.method=='GET':
        context={}
        context['name']=request.session.get('name')
        return render(request,'back/changePwd.html',context)
    else:
        #获取修改的数据，提示密码修改成功，请重新登陆，重定向到首页
        #获取新密码和确认密码
        oldpwd=request.POST['oldpass']
        newpwd=request.POST['newpass']
        repwd=request.POST['repass']
        u=UserService.getUsermima(request.session.get('name'))
        if u!=None and oldpwd!=u.pwd:
            return HttpResponse(UIResult(False,'输入旧密码不正确'),content_type='application/json')
        elif newpwd!=repwd:
            return HttpResponse(UIResult(False, '新密码和确认密码不一致'), content_type='application/json')
        else:
            #访问数据库进行密码更改
            uname='admin'#update user set password='{0}' where username='{1}'
            UserService.xiugaiPwd(uname,newpwd)
            return HttpResponse(UIResult(True))
#个人信息
def selfInfo(request):
    if request.method=='GET':
        uobj=UserService.findByname('admin')
        #print(uobj.selfphoto)
        return render(request,'back/selfInfo.html',{'uobj':uobj})
    else:
        id=request.POST['userid']
        selfSlogo=request.POST['selfSlogo']
        picUrl=request.POST['PicUrl']
        aboutMe=request.POST['aboutMe']
        result=UserService.updateInfo(id,selfSlogo,picUrl,aboutMe)
        if result:
            return HttpResponse(UIResult(True),content_type='application/json')
        else:
            return HttpResponse(UIResult(False,'修改失败'),content_type='application/json')
#文章管理
# def articles(request):
#     typelist = ArticleService.getType()
#     return render(request, 'back/articles.html',{'typelist':typelist})
def articles(request):
    uname=request.session.get('name')
    print(uname)
    if uname:
        typelist = ArticleService.getType()
        return render(request, 'back/articles.html', {'typelist': typelist})
    else:
        return render(request,'back/login.html',{'errorMsg':'请先登陆......'})
#相册管理
# def galleryes(request):
#     typelist = RecommentService.galleryType()
#     return render(request, 'back/gallery.html', {'typelist': typelist})
def galleryes(request):
    uname=request.session.get('name')
    print(uname)
    if uname:
        typelist = RecommentService.galleryType()
        return render(request, 'back/gallery.html', {'typelist': typelist})
    else:
        return render(request,'back/login.html',{'errorMsg':'请先登陆......'})
#推荐管理
def recommends(request):
    return render(request,'back/recomments.html')

#首页默认显示内容
def welcome(request):
    uobj = UserService.findByname('admin')
    return render(request,'back/welcome.html',{'uobj':uobj})
@csrf_exempt#运行跨域请求
def upload(request):
    if request.method=='POST':
        #获取上传的文件   request.FILES[name值]
        f=request.FILES['myFile']
        #得到项目的绝对路径
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        #对上传文件，重命名 uuid.uuid1()   不会出现两个相同的名字
        fileName='{0}.jpg'.format(uuid.uuid1())
        #拼接图片上传路径
        filrDir=os.path.join(BASE_DIR,'static/back/images/{0}'.format(fileName))
        with open(filrDir,'wb+') as fp:#wb+二进制的形式写入，写入文件的句柄
            #分块读取
            for info in f.chunks():#f.chunks()对上传的文件分块
                fp.write(info)  #写
            fp.close()#关闭链接
        return HttpResponse(UIResult(True,'','images/{0}'.format(fileName)),content_type='application/json')
    else:
        return HttpResponse(UIResult(True,'未检查到上传文件',),content_type='application/json')
#文章管理列表
def getArticleList(request):
    cur_page=request.GET.get('page')#页码
    pagesize=request.GET.get('limit')#每页中的几条数据
    title=request.GET.get('titlecontains')
    type=request.GET.get('type')
    ispub=request.GET.get('ispub')
    #查询文章列表txtTitle,type,ispub     '','',''
    alist=ArticleService.getAlist(title,type,ispub)#对象[aobj1,obj2,....]
    #1、文章列表通过字典存储    2、分页   3、json数据格式
    if alist:    #查询到结果的情况
        diclist=[]#type,tags,ispub,createtime,pubtime

        for a in alist:
            dict={}
            dict['id']=a.id
            dict['title']=a.title
            dict['type']=a.type
            dict['tags'] = a.tags
            dict['ispub'] = a.ispub
            dict['createtime'] = a.createtime
            dict['pubtime'] = a.pubtime
            diclist.append(dict)
        #分页
        paginator=Paginator(diclist,pagesize)
        #获取当前页码记录
        page_obj=paginator.get_page(cur_page)
        pagelist=[]
        for pobj in page_obj:
            pagelist.append(pobj)
        result = {"code": 0, "msg": "", "count": len(diclist), "data": pagelist}#服务器通过指定格式进行json字符串的数据响应
        # json.dumps(Result, cls=DateEncoder)没有时间字段问题可直接返回此代码。有就返回下面代码
        return HttpResponse(json.dumps(result, cls=DateEncoder), content_type="application/json")
    else:
        result = {"code": 0, "msg": "", "count": 0, "data": []}
        # json.dumps(Result, cls=DateEncoder)没有时间字段问题可直接返回此代码。有就返回下面代码
        return HttpResponse(json.dumps(result, cls=DateEncoder), content_type="application/json")
#文章管理添加
def addArticle(request):
    if request.method == 'GET':
        tagslist=ArticleService.getTags()
        typelist=ArticleService.getType()
        return render(request,'back/addArticles.html',{'tagslist':tagslist,'typelist':typelist})
    else:
        #执行添加文章的操作   1、获取界面上的传值 2、将值传入到数据访问层
        title=request.POST['title']
        tags=request.POST['tags']
        simpleinfo=request.POST['simpleinfo']
        cont = request.POST['cont']
        PicUrl = request.POST['PicUrl']
        source = request.POST['source']
        type = request.POST['type']
        ispub = request.POST.get('ispub')
        print(ispub)
        if ispub=='on':
            ispub='是'
        else:
            ispub='否'
        flag=ArticleService.save(title,tags,simpleinfo,cont,PicUrl,source,type,ispub)
        if flag:
            return HttpResponse(UIResult(True),content_type='application/json')
        else:
            return HttpResponse(UIResult(False,'添加失败'), content_type='application/json')
#文章管理删除
def expunge(request):
    id=request.GET.get('id')
    print(id)
    result=ArticleService.delete(id)
    if result:
        return HttpResponse(UIResult(True, '', '删除成功', ), content_type='application/json')
    else:
        return HttpResponse(UIResult(False, '删除操作失败', '', ), content_type='application/json')

#文章管理新增推荐
def addtuijian(request):
    if request.method=='GET':
        id=request.GET.get('id')
        aobj=ArticleService.findByid(id)
        if aobj:
            context={'aobj':aobj}
            return render(request,'back/addRecomment.html',context)
        else:
            raise Http404('推荐文章编号{0}不存在'.format(id))
    else:
        aid=request.POST['aid']
        posid=request.POST['posid']
        weight = request.POST['weight']
        #同一文章在相同位置不能重复推荐
        result=RecommentService.findByAidAndPid(aid,posid)
        if result:
            #新增推荐操作
            flag=RecommentService.save(aid,posid,weight)
            if flag:
                return HttpResponse(UIResult(True),content_type='application/json')
            else:
                return HttpResponse(UIResult(False,'推荐失败'),content_type='application/json')
        else:
            return HttpResponse(UIResult(False,'不能重复推荐'),content_type='application/json')
#文章管理批量删除
def batchDel(request):
    ids=request.GET.get('ids')
    result=ArticleService.batchDel(ids)
    if result:
        return HttpResponse(UIResult(True, '', '删除成功', ), content_type='application/json')
    else:
        return HttpResponse(UIResult(False, '删除操作失败', '', ), content_type='application/json')
#文章管理批量发布
def batchpub(request):
    ids = request.GET.get('ids')
    result = ArticleService.batchpub(ids)
    if result:
        return HttpResponse(UIResult(True, '', '发布成功', ), content_type='application/json')
    else:
        return HttpResponse(UIResult(False, '发布失败', '', ), content_type='application/json')
#文章管理编辑文章
def editArticle(request):
    if request.method=='GET':
        #渲染编辑界面
        aid=request.GET.get('aid')
        #根据aid查找文章记录
        aobj=ArticleService.findByid(aid)
        if aobj:
            tagslist = ArticleService.getTags()
            typelist = ArticleService.getType()
            context={'aobj':aobj,'tagslist':tagslist,'typelist':typelist}
            return render(request,'back/editArticles.html',context)
        else:
            raise Http404('编辑文章编号{0}不存在'.format(aid))
    else:
        id=request.POST['aid']
        title = request.POST['title']
        tags = request.POST['tags']
        simpleinfo = request.POST['simpleinfo']
        cont = request.POST['cont']
        picurl = request.POST['picurl']
        source = request.POST['source']
        type = request.POST['type']
        #print(id,title,tags,simpleinfo,cont,picurl,source,type)
        result=ArticleService.edit(id,title,tags,simpleinfo,cont,picurl,source,type)
        if result:
            return HttpResponse(UIResult(True),content_type="application/json")
        else:
            return HttpResponse(UIResult(False,'修改失败'),content_type="application/json")
#推荐列表
def getRecomment(request):
    cur_page = request.GET.get('page')  # 页码
    pagesize = request.GET.get('limit')  # 每页中的几条数据
    #搜索内容
    posid = request.GET.get('posid')
    min_weight = request.GET.get('min_weight')
    max_weight = request.GET.get('max_weight')
    # 查询推荐列表
    rlist = RecommentService.getrecommtnts(posid,min_weight,max_weight)
    # 1、文章列表通过字典存储    2、分页   3、json数据格式
    if rlist:  # 查询到结果的情况
        diclist = []
        for a in rlist:
            dict = {}
            dict['id'] = a.id
            dict['title'] = a.aobj.title #aobj是一个对象
            dict['showtype'] = a.aobj.showtype
            if a.posid==1:
                dict['posid'] = '网站首页'
            elif a.posid==2:
                dict['posid'] = '关于我'
            elif a.posid==3:
                dict['posid'] = '我的日记'
            dict['weight']=a.weight
            diclist.append(dict)
        # 分页
        paginator = Paginator(diclist, pagesize)
        # 获取当前页码记录
        page_obj = paginator.get_page(cur_page)
        pagelist = []#最终返回结果的集合
        for temp in page_obj:
            pagelist.append(temp)
        result = {"code": 0, "msg": "ok", "count": len(diclist), "data": pagelist}
        # json.dumps(Result, cls=DateEncoder)没有时间字段问题可直接返回此代码。有就返回下面代码
        return HttpResponse(json.dumps(result), content_type="application/json")
    else:
        result = {"code": 0, "msg": "ok", "count": 0, "data": []}
        # json.dumps(Result, cls=DateEncoder)没有时间字段问题可直接返回此代码。有就返回下面代码
        return HttpResponse(json.dumps(result), content_type="application/json")

#推荐管理   批量删除
def reBatchDel(request):
    ids = request.POST['ids']
    result = RecommentService.recommentDel(ids)
    if result:
        return HttpResponse(UIResult(True, '', '删除成功', ), content_type='application/json')
    else:
        return HttpResponse(UIResult(False, '删除操作失败', '', ), content_type='application/json')
#推荐列表  单条删除
def singleDel(request):
    id=request.GET.get('id')
    result=RecommentService.singleDel(id)
    if result:
        return HttpResponse(UIResult(True, '', '删除成功', ), content_type='application/json')
    else:
        return HttpResponse(UIResult(False, '删除操作失败', '', ), content_type='application/json')
#推荐列表 编辑
def redactRecomment(request):
    if request.method == 'GET':
        # 渲染编辑界面
        aid = request.GET.get('aid')
        # 根据aid查找文章记录
        robj = RecommentService.findById(aid)
        if robj:
            rlist=RecommentService.findAllpostion()
            context = {'robj': robj,'rlist':rlist}
            return render(request, 'back/editRecomments.html', context)
        else:
            raise Http404('编辑文章编号{0}不存在'.format(aid))
    else:

        id = request.POST['aid']
        weight = request.POST['weight']
        posid = request.POST['posid']
        print(id,weight,posid)
        result = RecommentService.edit(id,weight,posid)
        if result:
            return HttpResponse(UIResult(True), content_type="application/json")
        else:
            return HttpResponse(UIResult(False, '修改失败'), content_type="application/json")
# 相册管理
def getxiangce(request):
    cur_page = request.GET.get('page')  # 页码
    pagesize = request.GET.get('limit')  # 每页中的几条数据
    title = request.GET.get('titlecontains')
    type = request.GET.get('type')
    ispub = request.GET.get('ispub')
    # print(title)
    # print(type)
    # print(ispub)
    # 查询文章列表txtTitle,type,ispub     '','',''
    alist =RecommentService.getgallery(title, type, ispub)  # 对象[aobj1,obj2,....]
    # 1、文章列表通过字典存储    2、分页   3、json数据格式
    if alist:  # 查询到结果的情况
        diclist = []  # type,tags,ispub,createtime,pubtime
        for a in alist:
            dict = {}
            dict['id'] = a.id
            dict['title'] = a.title
            dict['type'] = a.type
            dict['tags'] = a.tags
            dict['ispub'] = a.ispub
            dict['mainpicurl'] = a.mainpicurl
            dict['createtime'] = a.createtime
            dict['pubtime'] = a.pubtime
            diclist.append(dict)
        # 分页
        paginator = Paginator(diclist, pagesize)
        # 获取当前页码记录
        page_obj = paginator.get_page(cur_page)
        pagelist = []
        for pobj in page_obj:
            pagelist.append(pobj)
        result = {"code": 0, "msg": "", "count": len(diclist), "data": pagelist}
        # json.dumps(Result, cls=DateEncoder)没有时间字段问题可直接返回此代码。有就返回下面代码
        return HttpResponse(json.dumps(result, cls=DateEncoder), content_type="application/json")
    else:
        result = {"code": 0, "msg": "", "count": 0, "data": []}
        # json.dumps(Result, cls=DateEncoder)没有时间字段问题可直接返回此代码。有就返回下面代码
        return HttpResponse(json.dumps(result, cls=DateEncoder), content_type="application/json")
# 添加相册
def addGallery(request):
    if request.method=='GET':
        taglist=RecommentService.gallerytags()
        typelist=RecommentService.galleryType ()
        return render(request,'back/addGallery.html',{'taglist':taglist,'typelist':typelist})
    else:
        title=request.POST['title']
        tags=request.POST['tags']
        SimpleInfo = request.POST['simpleinfo']
        Cont = request.POST['cont']
        Source = request.POST['source']
        type = request.POST['type']
        PicUrl=request.POST['PicUrl']
        IsPub = request.POST.get('ispub',False)
        if IsPub=='on':
            IsPub='是'
        else:
            IsPub='否'
        flag=RecommentService.gallerysave(title,tags,SimpleInfo,Cont,Source,type,PicUrl,IsPub,datetime.datetime.now())
        if flag:
            return HttpResponse(UIResult(True),content_type='application/json')
        else:
            return HttpResponse ( UIResult ( False,'添加失败' ), content_type='application/json' )
# 相册编辑
def editGallery(request):
    if request.method=='GET':
        aid = request.GET.get ( 'aid' )
        aobj=RecommentService.findgalleryById(aid)
        print(aid)
        if aobj:
            tagslist=ArticleService.getTagses()
            typelist=ArticleService.getTypese()
            context={'aobj':aobj,'tagslist':tagslist,'typelist':typelist}
            return render(request,'back/editGallery.html',context)
        else:
            raise Http404('编辑文章编号{0}不存在'.format(aid))
    else:
        title = request.POST['title']
        tags = request.POST['tags']
        SimpleInfo = request.POST['simpleinfo']
        Cont = request.POST['cont']
        PicUrl=request.POST['PicUrl']
        Source = request.POST['source']
        type = request.POST['type']
        aid = request.POST[ 'aid' ]
        print(aid)
        result=ArticleService.edit( title, tags,SimpleInfo,Cont,PicUrl,Source,type,aid)
        if result:
            return HttpResponse(UIResult(True),content_type='application/json')
        else:
            return HttpResponse ( UIResult ( False,'编辑失败' ), content_type='application/json' )
#相册管理删除
def xcdelect(request):
    id=request.GET.get('id')
    result=ArticleService.delete(id)
    if result:
        return HttpResponse(UIResult(True, '', '删除成功', ), content_type='application/json')
    else:
        return HttpResponse(UIResult(False, '删除操作失败', '', ), content_type='application/json')
def tianjiaxiangcetj(request):
    if request.method=='GET':
        id=request.GET.get('id')
        aobj=RecommentService.findgalleryById(id)
        if aobj:
            context={'aobj':aobj}
            return render(request,'back/addRecommentes.html',context)
        else:
            raise Http404('推荐文章编号{0}不存在'.format(id))
    else:
        aid=request.POST['aid']
        posid=request.POST['posid']
        weight = request.POST['weight']
        #同一文章在相同位置不能重复推荐
        result=RecommentService.findByAidAndPid(aid,posid)
        if result:
            #新增推荐操作
            flag=RecommentService.save(aid,posid,weight)
            if flag:
                return HttpResponse(UIResult(True),content_type='application/json')
            else:
                return HttpResponse(UIResult(False,'推荐失败'),content_type='application/json')
        else:
            return HttpResponse(UIResult(False,'不能重复推荐'),content_type='application/json')